package com.supplychainapi.service.impl.supplier;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.BizCode;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.dao.prod.ScmTbsupplierMapper;
import com.supplychainapi.domain.IncrementRate;
import com.supplychainapi.model.ScmTbseqno;
import com.supplychainapi.model.ScmTbsupplier;
import com.supplychainapi.model.ScmTbsupplierExtend;
import com.supplychainapi.model.ScmTbtreebuild;
import com.supplychainapi.param.ColTitle;
import com.supplychainapi.service.IScmTbsupplierService;
import com.supplychainapi.service.IScmTbtreebuildService;
import com.supplychainapi.service.TbMaterialService;
import com.supplychainapi.service.TbSeqNoService;
import com.supplychainapi.utils.Constants;
import com.supplychainapi.utils.HelpCodeUtils;
import com.supplychainapi.utils.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 *
 * 供应商
 * @author:xiezhiwei
 * @email:xiezhiwei@niwodai.net
 * @date:2017-09-26
 *
 */
@Service
public class ScmTbsupplierServiceImpl implements IScmTbsupplierService{

	private Logger logger = LogManager.getLogger(ScmTbsupplierServiceImpl.class);

	@Autowired
	private ScmTbsupplierMapper scmTbsupplierMapper;

	@Autowired
	private TbMaterialService materialService;

	@Autowired
	TbSeqNoService tbSeqNoService;
	@Autowired
	private IScmTbtreebuildService treebuildService;

	@Override
	public void addScmTbsupplierInfo(ScmTbsupplier supplier) throws ServiceException {
		if(StringUtil.checkIsEmoji(supplier.getFsSupplierName())){
			throw ExceptionMessage.emoji_failed.getServiceException();
		}
		if(supplier.getFsSupplierId()==null || supplier.getFsSupplierId().trim().equals("")){
			logger.info("----开始自动生成编号-----");
			ScmTbseqno model = new ScmTbseqno();
			model.setFsShopGUID(supplier.getFsShopGUID());
			model.setFsCls(Constants.SUPPLIER_CLASS);
			String fsSupplierId = tbSeqNoService.selectSeqNo(model);
			supplier.setFsSupplierId(fsSupplierId);
		}else{
			logger.info("手动填写编号业务处理");
			ScmTbseqno tbseqno1 = new ScmTbseqno();
			tbseqno1.setFiSeqNo(supplier.getFsSupplierId());
			tbseqno1.setFsCls(Constants.SUPPLIER_CLASS);
			tbseqno1.setFsShopGUID(supplier.getFsShopGUID());
			tbSeqNoService.checkCode(tbseqno1);
			tbSeqNoService.insert(tbseqno1, supplier.getFsShopGUID());
		}
		//根据挂载的节点ID，找到父级的的信息
		String fsNodeCode = supplier.getFsNodeCode();
		List<ScmTbtreebuild> treeList = treebuildService.getParentNodeCodeAndNodeCodeInfo(supplier.getFsShopGUID(), Constants.SUPPLIER_CLASS, fsNodeCode);
		String fsNodeFullText = "";
		if (treeList != null && treeList.size() > 0) {
			for (ScmTbtreebuild scmTbtreebuild : treeList) {
				fsNodeFullText = fsNodeFullText.concat(scmTbtreebuild.getFsNodeFullText() + "_");
			}
		}
		supplier.setFsNodeFullText(fsNodeFullText.concat(supplier.getFsSupplierName()));
		supplier.setFsCreateTime(new Date());
		supplier.setFsUpdateTime(new Date());
		supplier.setFsHelpCode(HelpCodeUtils.String2Alpha(supplier.getFsSupplierName()));
		scmTbsupplierMapper.insertSelective(supplier);
	}

	@Override
	public void updateScmTbsupplierInfo(ScmTbsupplier supplier) throws ServiceException {
		supplier.setFsHelpCode(HelpCodeUtils.String2Alpha(supplier.getFsSupplierName()));
		scmTbsupplierMapper.updateByPrimaryKeySelective(supplier);
	}

	@Override
	public ScmTbsupplier getSupplierByFsSupplierNameInfo(String fsSupplierName) throws ServiceException {
		logger.info("----fsSupplierName----"+fsSupplierName);
		ScmTbsupplier scmTbsupplier = scmTbsupplierMapper.getSupplierByFsSupplierNameInfo(fsSupplierName);
		return scmTbsupplier;
	}

	@Override
	public ScmTbsupplier getSupplierInfo(String fsSupplierId) {
		logger.info("fsSupplierId={}",fsSupplierId);
		ScmTbsupplier scmTbsupplier = scmTbsupplierMapper.getSupplierInfo(fsSupplierId);
		return scmTbsupplier;
	}

	@Override
	public List<ScmTbsupplier> getSupplierByfsNodeFullTextList(String fsShopGUID,String fsNodeFullText, Integer page, Integer pageSize) throws ServiceException{
		if(page!=null){
			page = (page-1) * pageSize;
		}else{
			page = 0;
		}
		List<ScmTbsupplier> scmTbsupplierList = scmTbsupplierMapper.getSupplierByfsNodeFullTextList(fsShopGUID,fsNodeFullText,page,pageSize);
		return scmTbsupplierList;
	}

	@Override
	public void deleteSupplierInfo(List<String> fsSupplierIdList, List<String> fsShopGUIDList) throws ServiceException {
		if(fsSupplierIdList==null || fsSupplierIdList.size()<=0){
			throw new ServiceException(BizCode.FAIL.getNum(), BizCode.PARAM_NULL.getDesc());
		}

		if(fsShopGUIDList==null || fsShopGUIDList.size()<=0){
			throw new ServiceException(BizCode.FAIL.getNum(), BizCode.PARAM_NULL.getDesc());
		}
		for (String supplierId : fsSupplierIdList) {
			Integer count = materialService.supplierQuotes(null, supplierId);
			if(count!=null && count>0){
				throw new ServiceException(BizCode.FAIL.getNum(), BizCode.SUPPLIER_QUOTE_ERROR_MESSAGE.getDesc());
			}
		}
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("fsSupplierIdList", fsSupplierIdList);
		parameterMap.put("fsShopGUIDList", fsShopGUIDList);
		scmTbsupplierMapper.deleteSupplierInfo(parameterMap);
	}

	@Override
	public List<ScmTbsupplier> getByKeyWordSupplierInfoList(String keyWord, Integer page, Integer pageSize)
			throws ServiceException {
		if(page!=null){
			page = (page-1) * pageSize;
		}else{
			page = 0;
		}
		List<ScmTbsupplier> scmTbsupplierList = scmTbsupplierMapper.getByKeyWordSupplierInfoList(keyWord,page,pageSize);
		return scmTbsupplierList;
	}

	@Override
	public ScmTbsupplier getSupplierByFsShopGUIDList(String fsShopGUID, String fsSupplierId)
			throws ServiceException {
		ScmTbsupplier scmTbsupplier = scmTbsupplierMapper.getSupplierByFsShopGUIDList(fsShopGUID,fsSupplierId);
		return scmTbsupplier;
	}

	@Override
	public List<ScmTbsupplierExtend> getSupplierAllListInfo(String fsShopGUID, Integer page, Integer pageSize)
			throws ServiceException {
		logger.info("fsShopGUID={},page={},pageSize={}",fsShopGUID,page,pageSize);
		if(page!=null){
			page = (page-1) * pageSize;
		}else{
			page = 0;
		}
		List<ScmTbsupplierExtend> supplierAllListInfo = scmTbsupplierMapper.getSupplierAllPhoneListInfo(fsShopGUID, page, pageSize);
		return supplierAllListInfo;
	}

	@Override
	public Boolean getSupplierNameIsExit(String fsShopGUID, String fsSupplierName,String fsSupplierId,String type) throws ServiceException {
		logger.info("判断供应商名称是否重复 fsShopGUID={},fsStorageName={},fsStorageId={},type={}",fsShopGUID,fsSupplierName,fsSupplierId,type);
		Integer countNumber = scmTbsupplierMapper.getSupplierNameIsExit(fsShopGUID, fsSupplierName);
		if(type.equals("update")){
			//当前传入的供应用名称和数据库查询出来的名称相同不做处理
			ScmTbsupplier supplier = scmTbsupplierMapper.getSupplierByFsShopGUIDList(fsShopGUID, fsSupplierId);
			if(supplier!=null && supplier.getFsSupplierName().equals(fsSupplierName)){
				return false;
			}
		}
		logger.info("根据当前门店和供应商名查询返回结果集="+countNumber);
		return countNumber != null && countNumber > 0;
	}


	@Override
	public int count(ScmTbsupplier param) {
		return scmTbsupplierMapper.selectCount(param);
	}


	@Override
	public List<ColTitle> getSchema() {
		List<ColTitle> list = new ArrayList<ColTitle>();
		list.add(new ColTitle("fsSupplierId", "供应商代码", "center", 100));
		list.add(new ColTitle("fsSupplierName", "供应商名称", "center", 100));
		list.add(new ColTitle("fsContact", "联系人", "center", 100));
		list.add(new ColTitle("fsCellphoneCt", "联系手机", "center", 100));
		list.add(new ColTitle("fiStatus", "状态", "center", 100));
		list.add(new ColTitle("__EDIT__", "操作", null, 150, "fsSupplierId"));
		return list;
	}


	@Override
	public PageInfo getSupplierListInfo(String fsShopGUID, String keyWord, String fsNodeCode, Integer pageNum,
										Integer pageSize) throws ServiceException {
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy("fsCreateTime DESC");
		List<ScmTbsupplier> supplierList = scmTbsupplierMapper.getSupplierListInfo(fsShopGUID, keyWord, fsNodeCode);
		return new PageInfo(supplierList);
	}

	/*
	@Override
	public List<ScmTbsupplier> getSupplierListInfo(String fsShopGUID, String keyWord, String fsNodeCode, Integer pageNum,
			Integer pageSize) throws ServiceException{
		if(pageNum!=null){
			pageNum = (pageNum-1) * pageSize;
		}else{
			pageNum = 0;
		}
        List<ScmTbsupplier> supplierList = scmTbsupplierMapper.getSupplierListInfo(fsShopGUID,keyWord,fsNodeCode,pageNum,pageSize);
        return supplierList;
	}*/

	/*
	@Override
	public List<ScmTbsupplier> getChoiceSupplierListInfo(String fsShopGUID, String keyWord, String fsNodeCode,
			Integer pageNum, Integer pageSize) {
		if(pageNum!=null){
			pageNum = (pageNum-1) * pageSize;
		}else{
			pageNum = 0;
		}
        List<ScmTbsupplier> supplierList = scmTbsupplierMapper.getChoiceSupplierListInfo(fsShopGUID,keyWord,fsNodeCode,pageNum,pageSize);
        return supplierList;
	}*/

	@Override
	public PageInfo getChoiceSupplierListInfo(String fsShopGUID, String keyWord, String fsNodeCode,
											  Integer pageNum, Integer pageSize) throws ServiceException {
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy("fsCreateTime DESC");
		List<ScmTbsupplier> supplierList = scmTbsupplierMapper.getChoiceSupplierListInfo(fsShopGUID, keyWord, fsNodeCode);
		return new PageInfo(supplierList);
	}

	@Override
	public ScmTbsupplier getSupplierDetails(String fsShopGUID, String fsSupplierId) throws ServiceException {
		ScmTbsupplier supplier = scmTbsupplierMapper.getSupplierPhoneDetailsInfo(fsShopGUID, fsSupplierId);
		return supplier;
	}

	@Override
	public Map<String, List<IncrementRate>> getIncrementRate() {
		Map<String, List<IncrementRate>> map = Maps.newHashMap();
		List<IncrementRate> listIncrementRate = Lists.newArrayList();
		listIncrementRate.add(new IncrementRate("0", "0"));
		listIncrementRate.add(new IncrementRate("3", "3"));
		listIncrementRate.add(new IncrementRate("6", "6"));
		listIncrementRate.add(new IncrementRate("11", "11"));
		listIncrementRate.add(new IncrementRate("13", "13"));
		listIncrementRate.add(new IncrementRate("17", "17"));
		map.put("listIncrementRate", listIncrementRate);
		return map;
	}

	@Override
	public ScmTbsupplierExtend getSupplierDetailsInfo(String fsShopGUID, String fsSupplierId) {
		ScmTbsupplierExtend supplierExtend = scmTbsupplierMapper.getSupplierDetailsInfo(fsShopGUID, fsSupplierId);
		return supplierExtend;
	}


	/******************************* 手机端接口********************************************/

	@Override
	public void addScmTbsupplierPhoneInfo(ScmTbsupplier supplier) throws ServiceException {
		logger.info("手机版新增供应商");
		if (StringUtil.checkIsEmoji(supplier.getFsSupplierName())) {
			throw ExceptionMessage.emoji_failed.getServiceException();
		}
		if (supplier.getFsSupplierId() == null || supplier.getFsSupplierId().trim().equals("")) {
			logger.info("----开始自动生成编号-----");
			ScmTbseqno model = new ScmTbseqno();
			model.setFsShopGUID(supplier.getFsShopGUID());
			model.setFsCls(Constants.SUPPLIER_CLASS);
			String fsSupplierId = tbSeqNoService.selectSeqNo(model);
			supplier.setFsSupplierId(fsSupplierId);
			tbSeqNoService.checkCode(model);
			tbSeqNoService.insert(model, supplier.getFsShopGUID());
		} else {
			logger.info("手动填写编号业务处理");
			ScmTbseqno tbseqno1 = new ScmTbseqno();
			tbseqno1.setFiSeqNo(supplier.getFsSupplierId());
			tbseqno1.setFsCls(Constants.SUPPLIER_CLASS);
			tbSeqNoService.checkCode(tbseqno1);
			tbSeqNoService.insert(tbseqno1, supplier.getFsShopGUID());
		}
		//supplier.setFsNodeFullText(supplier.getFsNodeFullText().concat("_"+supplier.getFsSupplierName()));

		//根据挂载的节点ID，找到父级的的信息
		String fsNodeCode = supplier.getFsNodeCode();
		List<ScmTbtreebuild> treeList = treebuildService.getParentNodeCodeAndNodeCodeInfo(supplier.getFsShopGUID(), Constants.SUPPLIER_CLASS, fsNodeCode);
		String fsNodeFullText = "";
		if (treeList != null && treeList.size() > 0) {
			for (ScmTbtreebuild scmTbtreebuild : treeList) {
				fsNodeFullText = fsNodeFullText.concat(scmTbtreebuild.getFsNodeText() + "_");
			}
		}
		supplier.setFsNodeFullText(fsNodeFullText.concat(supplier.getFsSupplierName()));
		supplier.setFsHelpCode(HelpCodeUtils.String2Alpha(supplier.getFsSupplierName()));
		supplier.setFsCreateTime(new Date());
		supplier.setFsUpdateTime(new Date());
		scmTbsupplierMapper.insertSelective(supplier);
	}

	@Override
	public void updateScmTbsupplierPhoneInfo(ScmTbsupplier supplier) throws ServiceException {
		logger.info("更新供应商信息fsNodeCode = " + supplier.getFsNodeCode());
		supplier.setFsHelpCode(HelpCodeUtils.String2Alpha(supplier.getFsSupplierName()));
		List<ScmTbtreebuild> treeList = treebuildService.getParentNodeCodeAndNodeCodeInfo(supplier.getFsShopGUID(), Constants.SUPPLIER_CLASS, supplier.getFsNodeCode());
		String fsNodeFullText = "";
		if (treeList != null && treeList.size() > 0) {
			for (ScmTbtreebuild scmTbtreebuild : treeList) {
				fsNodeFullText = scmTbtreebuild.getFsNodeFullText();
			}
		}
		supplier.setFsNodeFullText(fsNodeFullText.concat("_" + supplier.getFsSupplierName()));
		supplier.setFsUpdateTime(new Date());
		int countPrimaryKeySelective = scmTbsupplierMapper.updateByPrimaryKeySelective(supplier);

		logger.info("更新影响行数 countPrimaryKeySelective={}", countPrimaryKeySelective);
	}

	@Override
	public List<ScmTbsupplier> getSupplierPhoneListInfo(String fsShopGUID, String fsNodeCode, Integer page, Integer pageSize)
			throws ServiceException {
		logger.info("fsShopGUID={},fsNodeCode={},page={},pageSize={}", fsShopGUID, fsNodeCode, page, pageSize);
		if (page != null) {
			page = (page - 1) * pageSize;
		} else {
			page = 0;
		}
		List<ScmTbsupplier> supplierListInfo = scmTbsupplierMapper.getSupplierPhoneListInfo(fsShopGUID, fsNodeCode, page, pageSize);
		return supplierListInfo;
	}

	@Override
	public List<ScmTbsupplierExtend> getSupplierPhoneByFsSupplierNameListInfo(String fsShopGUID, String fsSupplierName,
																			  Integer page, Integer pageSize) throws ServiceException {
		logger.info("fsShopGUID={},fsSupplierName={},page={},pageSize={}", fsShopGUID, fsSupplierName, page, pageSize);
		if (page != null) {
			page = (page - 1) * pageSize;
		} else {
			page = 0;
		}
		List<ScmTbsupplierExtend> supplierByNameListInfo = scmTbsupplierMapper.getSupplierPhoneByFsSupplierNameListInfo(fsShopGUID, fsSupplierName, page, pageSize);
		return supplierByNameListInfo;
	}

	@Override
	public void deletePhoneSupplierInfo(List<String> fsSupplierIdList, List<String> fsShopGUIDList)
			throws ServiceException {
		if (fsSupplierIdList == null || fsSupplierIdList.size() <= 0) {
			throw new ServiceException(BizCode.FAIL.getNum(), BizCode.PARAM_NULL.getDesc());
		}

		if (fsShopGUIDList == null || fsShopGUIDList.size() <= 0) {
			throw new ServiceException(BizCode.FAIL.getNum(), BizCode.PARAM_NULL.getDesc());
		}
		for (String supplierId : fsSupplierIdList) {
			Integer count = materialService.supplierQuotes(null, supplierId);
			if (count != null && count > 0) {
				throw new ServiceException(BizCode.FAIL.getNum(), BizCode.SUPPLIER_QUOTE_ERROR_MESSAGE.getDesc());
			}
		}
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("fsSupplierIdList", fsSupplierIdList);
		parameterMap.put("fsShopGUIDList", fsShopGUIDList);
		scmTbsupplierMapper.deleteSupplierInfo(parameterMap);
	}

	@Override
	public ScmTbsupplierExtend getSupplierPhoneDetailsInfo(String fsShopGUID, String fsSupplierId) throws ServiceException {
		ScmTbsupplierExtend supplierDetailsInfo = scmTbsupplierMapper.getSupplierPhoneDetailsInfo(fsShopGUID, fsSupplierId);
		return supplierDetailsInfo;
	}

	@Override
	public List<ScmTbsupplierExtend> getSupplierAllPhoneListInfo(String fsShopGUID, Integer page, Integer pageSize) throws ServiceException {
		logger.info("fsShopGUID={},page={},pageSize={}", fsShopGUID, page, pageSize);
		if (page != null) {
			page = (page - 1) * pageSize;
		} else {
			page = 0;
		}
		List<ScmTbsupplierExtend> supplierAllListInfo = scmTbsupplierMapper.getSupplierAllPhoneListInfo(fsShopGUID, page, pageSize);
		return supplierAllListInfo;
	}

	@Override
	public List<ScmTbsupplierExtend> getSupplierParentAllPhoneListInfo(String fsShopGUID, String fsNodeCode, Integer page,
																	   Integer pageSize) throws ServiceException {
		logger.info("fsShopGUID={},page={},pageSize={}", fsShopGUID, page, pageSize);
		if (page != null) {
			page = (page - 1) * pageSize;
		} else {
			page = 0;
		}
		List<ScmTbsupplierExtend> supplierParentAllListInfo = scmTbsupplierMapper.getSupplierParentAllPhoneListInfo(fsShopGUID, fsNodeCode, page, pageSize);
		return supplierParentAllListInfo;
	}


	@Override
	public List<ScmTbsupplier> getHeadquartersSupplierInfo(String fsShopGUID) throws ServiceException {

		List<ScmTbsupplier> supplierListInfo = scmTbsupplierMapper.getHeadquartersSupplierInfo(fsShopGUID);

		return supplierListInfo;
	}

	@Override
	public int updateFullText(ScmTbsupplier supplier) {
		Example example = new Example(ScmTbsupplier.class);
		example.createCriteria().andEqualTo("fsSupplierId", supplier.getFsSupplierId()).andEqualTo("fsShopGUID", supplier.getFsShopGUID());
		supplier.setFsNodeFullText(supplier.getFsNodeFullText().concat("_").concat(supplier.getFsSupplierName()));
		return scmTbsupplierMapper.updateByExampleSelective(supplier, example);
	}

	@Override
	public List<ScmTbsupplier> findFullCode(String fsShopGuid, String fullCode) throws ServiceException {
		Example example = new Example(ScmTbsupplier.class);
		example.createCriteria().andEqualTo("fsShopGUID", fsShopGuid).andLike("fsNodeFullCode", "%".concat(fullCode).concat("%"));
		return scmTbsupplierMapper.selectByExample(example);
	}

    @Override
    public List<ScmTbsupplierExtend> getSupplierKeyWordListInfo(String fsShopGUID, String keyWords, Integer page,
                                                                Integer pageSize) throws ServiceException {
        logger.info("fsShopGUID={},fsSupplierName={},page={},pageSize={}", fsShopGUID, keyWords, page, pageSize);
        if (page != null) {
            page = (page - 1) * pageSize;
        } else {
            page = 0;
        }
        List<ScmTbsupplierExtend> supplierByNameListInfo = scmTbsupplierMapper.getSupplierKeyWordListInfo(fsShopGUID, keyWords, page, pageSize);
        return supplierByNameListInfo;
    }
}
